<template>
  <view class="overall">
    <view v-if="dataInfo==null" class="empty-tip">暂无内容</view>
    <view class="content" v-else>
      <view class="one">
        <image class="imgs" :src="BASE_API_URL + '/' + dataInfo.avatar" mode="aspectFill"></image>
        <view>
          <view>
            <view>
              <view style="font-weight: bold; font-size: 32rpx;margin-right: 35rpx;">{{dataInfo.name}}
              </view>
              <view>{{dataInfo.duties}}</view>
            </view>
            <view>{{dataInfo.sex==1?'男':'女'}}</view>
            <view v-if="cardInfo===1" @click="collect(dataInfo.id)" class="icon-star">☆</view>
            <view v-if="cardInfo===2" @click="exiled(delId)" class="icon-star">★</view>
          </view>
          <view>检查费：{{dataInfo.money}}元</view>
          <view class="goods">{{dataInfo.good}}</view>
        </view>
      </view>
      <view class="choose">
        <view :class="{active: checked===1}" @click="choose(1)">医生简介</view>
        <view :class="{active: checked===2}" @click="choose(2)">出诊信息</view>
      </view>
      <view class="inner">
        <view v-if="checked===1" class="doctor-intro">
          <view v-html="dataInfo.content"></view>
        </view>
        <view v-if="checked===2" class="doctor-schedule">
          <!-- 医生信息 -->
          <view class="doctor-card" v-if="office.length > 0">
            <view style="background-color: white; margin-top: 10px; padding: 20rpx;">
              <!-- 医生介绍 -->
              <view class="doctor-introduction">
                {{ office[0].doctor.good }}
              </view>
              
              <!-- 分隔线 -->
              <view class="divider" style="margin: 20rpx 0;"></view>
              
              <!-- 价格和预约按钮 -->
              <view class="price-and-button" style="display: flex; justify-content: space-between; align-items: center;">
                <view class="price">￥ {{ office[0].doctor.money }}</view>
                <view class="booking-btn" @click="handleBooking(office[0], office[0].office[0])">预约</view>
              </view>
            </view>
          </view>
          
          <wd-status-tip image-size="60" v-else image="content" tip="暂无内容" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import { BASE_API_URL } from '@/utils/config'; // 导入配置
import { 
  work, 
  details, 
  favorites, 
  collectAdd, 
  collectDel,
  doctorList,
  doctorSchedule,
  doctorDetails 
} from '@/api/index.js';

function handleClickLeft() {
  uni.navigateBack();
}

const dataInfo = ref(null);
const cardInfo = ref(1);
const doctor = ref([]);
const office = ref([]);
const checked = ref(1);
const userInfo = ref(null);
const delId = ref(null);
const availableNumbers = ref({}); // 存储可用号源数量

// 在组件挂载时获取设备信息
onMounted(() => {
  // 获取医生详情信息
  uni.getStorage({
    key: 'details',
    success: function(res) {
      dataInfo.value = res.data;
      // 获取出诊信息（不限制医生）
      if (res.data) {
        fetchDoctorData(res.data.id);
      }
    }
  });
  
  // 检查是否已收藏
  collectible();
});

// 获取医生信息 - 修改后获取所有医生的信息
const fetchDoctorData = async (doctorId) => {
  try {
    // 获取医生所在科室ID（这里假设从dataInfo中获取）
    const departId = dataInfo.value?.depart_id || 0;
    
    if (!departId) return;
    
    // 获取医生列表
    const response = await doctorList({
      depart_id: departId
    });

    if (response.data) {
      // 找到当前医生信息
      const currentDoctor = response.data.find(item => item.id === doctorId);
      
      if (currentDoctor) {
        // 获取当前日期
        const today = new Date();
        const formattedDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

        // 获取医生排班信息（使用当前日期）
        const schedulingResponse = await doctorSchedule({
          depart_id: currentDoctor.depart_id,
          date: formattedDate,
        });

        let officeData = schedulingResponse.data;
        officeData = Array.isArray(officeData) ? officeData.sort((a, b) => a.time - b.time) : [officeData];

        // 获取可用号源数量
        await fetchAvailableNumbers(currentDoctor.id);
        
        // 更新office数据
        office.value = [{
          doctor: currentDoctor,
          office: officeData,
        }];
      }
    }
  } catch (error) {
    console.error('获取医生信息失败:', error);
  }
};

// 获取可用号源数量
async function fetchAvailableNumbers(doctorId) {
  try {
    const response = await doctorDetails({
      doctor_id: doctorId
    });
    
    if (response.data && response.data.children) {
      availableNumbers.value = {
        ...availableNumbers.value,
        [doctorId]: response.data.children.length
      };
    }
  } catch (error) {
    console.error(`获取医生ID=${doctorId}的可用号源失败:`, error);
  }
}

// 检查是否已收藏
function collectible() {
  uni.getStorage({
    key: 'user',
    success: function(res) {
      userInfo.value = res.data.id;
      favorites({
        user_id: res.data.id,
      }).then(res => {
        if (res.data != null) {
          let fruitList = res.data.doctor.filter(item => item.id == dataInfo.value.id);
          if (fruitList.length != 0) {
            cardInfo.value = 2;
            let collectIist = res.data.collect.filter(item => item.doctor_id == fruitList[0].id);
            delId.value = collectIist[0].id;
          }
        }
      })
    }
  });
}

// 添加收藏
function collect(id) {
  if (cardInfo.value === 1) {
    collectAdd({
      doctor_id: id,
      user_id: userInfo.value,
    }).then(res => {
      if (res.code === 1) {
        uni.showToast({
          title: '收藏添加成功',
          icon: 'none',
          duration: 2000
        });
        cardInfo.value = 2;
      } else {
        uni.showToast({
          title: '收藏添加失败',
          icon: 'none',
          duration: 2000
        });
      }
      collectible();
    })
  }
}

// 取消收藏
function exiled(id) {
  if (cardInfo.value === 2) {
    uni.showModal({
      title: '提示',
      content: '是否取消收藏',
      showCancel: true,
      success: function(res) {
        if (res.confirm) {
          collectDel({
            id: id,
          }).then(res => {
            if (res.code === 1) {
              uni.showToast({
                title: '取消收藏成功',
                icon: 'none',
                duration: 2000,
              });
              cardInfo.value = 1;
            } else {
              uni.showToast({
                title: '取消收藏失败',
                icon: 'none',
                duration: 2000
              });
            }
            collectible();
          })
        }
      }
    })
  }
}

// 选项卡切换
function choose(index) {
  checked.value = index;
  // 如果切换到出诊信息，获取数据
  if (index === 2 && dataInfo.value) {
    fetchDoctorData(dataInfo.value.id);
  }
}

// 处理预约逻辑 - 修改后所有医生都可以预约
const handleBooking = (doctorItem, scheduleItem) => {
  navigateToBookingPage(doctorItem, scheduleItem);
};

// 跳转到预约页面
const navigateToBookingPage = (doctorItem, scheduleItem) => {
  const bookingData = {
    doctor: doctorItem.doctor,
    schedule: scheduleItem,
    availableNumber: availableNumbers.value[doctorItem.doctor.id] || 0
  };
  uni.setStorageSync('bookingData', JSON.stringify(bookingData)); // 保存选中的医生和排班信息
  console.log('Stored Booking Data:', bookingData);
  uni.navigateTo({
    url: `/pages/sure/sure`
  });
};
</script>

<style scoped>
/* 样式部分保持不变 */
.overall {
  width: 100%;
  background-color: #F0F8FF;
  min-height: 100vh;
}

.empty-tip {
  padding: 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.content {
  width: 100%;
}

.imgs {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 1000rpx;
  overflow: hidden; /* 确保圆角生效 */
}

.one {
  width: 90%;
  padding: 29rpx 5%;
  display: flex;
  justify-content: space-between;
  background-color: #00DACA;
  color: white;
}

.one>view {
  width: 78%;
}

.one>view>view:first-child {
  display: flex;
  justify-content: space-between;
}

.one>view>view:first-child view {
  display: flex;
}

.one>view>view {
  margin-bottom: 30rpx;
}

.choose {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom: 2rpx #ECECEC solid;
  position: absolute;
  top: 18vh;
}

.choose>view {
  width: 24%;
  height: 100rpx;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1rpx #ECECEC solid;
  border-radius: 5rpx;
}

.choose .active {
  color: aquamarine;
}

.inner {
  margin-top: 60rpx;
}

.doctor-intro {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  line-height: 1.8;
  background-color: white;
  border-radius: 10rpx;
}

.doctor-intro p {
  margin-bottom: 15rpx;
}

.icon-star {
  font-size: 22px;
  cursor: pointer;
}

.goods {
  height: 45px;
  overflow: hidden;
}

.imgs {
  object-fit: cover;
}

/* 医生卡片样式 */
.doctor-card {
  padding: 0 15rpx;
}

.doctor-introduction {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.price-and-button {
  padding: 10rpx 0;
}

.price {
  color: #EC5C28;
  font-size: 32rpx;
  font-weight: bold;
}

.booking-btn {
  background-color: #2EC7C9;
  color: white;
  width: 120rpx;
  padding: 12rpx 5rpx;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

/* 分隔线样式 */
.divider {
  height: 1rpx;
  background-color: #E5E5E5;
  width: 100%;
}
</style>